<template>
	<div class="video—— i_maxW">
		<div class="prepare-crumbs">
		    <router-link to="/prepare">备课<i>></i></router-link>
		    <span @click="goBack">{{$route.query.name}} </span>
		    <span><i>></i>视频</span>
		</div>
		<div class="conten-box">
			<ul class="clear"  v-loading="loading"  element-loading-text="拼命加载中">
				<li class="fl task-list" v-for="item of videoList" >
					<a  @click="checkLook(item, item.res_id, 0)" class="task-list-name">{{item.videoname}}</a>

					<div class="task-list-info clear">

						<div class="task-list-info-l fl">
							<div class="task-list-info-l-img box">
								<img src="../../../../public/images/Group9.png" >
							</div>
							<div class="task-list-info-l-txt box">
								<span>{{item.username}}</span>
								<span>{{getDateDiff(item.create_time)}}</span>
							</div>
						</div>

						<div class="task-list-info-r fr">
							<el-popover
							    placement="bottom-start"
							    width="50"
							    trigger="hover"
							    popper-class="task-popover"
							    content="发任务">
							    <button class="p-task new" slot="reference" @click="newTaskVisible(item.res_id)"></button>
							</el-popover>
							<el-popover
							    placement="bottom-start"
							    width="50"
							    trigger="hover"
							    popper-class="task-popover"
							    content="下载">
							    <a :href="download(0, item.res_id)" class="p-task de" slot="reference"></a>
							</el-popover>
							<el-popover
							    placement="bottom-start"
							    width="50"
							    trigger="hover"
							    popper-class="task-popover"
							    content="删除">
							   <button class="p-task del" slot="reference" @click="removeDate(item.res_id)"></button>
							</el-popover>
							
						</div>
					</div>
				</li>
			</ul>
			<template>
			  <el-pagination
			  		v-if="total_sum > page_size"
			       @current-change="sizeChange"
			       :current-page.sync="page_index"
			       :page-size="page_size"
			       layout="total, prev, pager, next"
			       :total="total_sum">
			  </el-pagination>
			</template>
			<!--  -->
			<div class="dependent" v-if="placeholder">
				<i class="ipng image_state01"></i>
				<p>还没发现任何相关的内容哦~</p>
			</div>
		</div>

		<el-dialog title="发布任务" :visible.sync="taskVisible" width="550px" custom-class="alBox" :close-on-click-modal="false">

		    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
		        <el-form-item label="任务名称" prop="name">
		            <el-input v-model="ruleForm.name" placeholder="20个字符以内" maxlength="20"></el-input>
		        </el-form-item>

		        <el-form-item label="任务对象" prop="class_id">
		            <el-checkbox-group v-model="ruleForm.class_id">
		                <el-checkbox :label="item.id" name="type" v-for="item of classLsit" :key="item.id">{{item.rename}}</el-checkbox>
		            </el-checkbox-group>
		        </el-form-item>



		        <el-form-item label="截止时间" required>
		            <el-col :span="11">
		                <el-form-item prop="date">
		                    <el-date-picker type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" v-model="ruleForm.date" style="width: 100%;" :picker-options="pickerOptionsStart"></el-date-picker>
		                </el-form-item>
		            </el-col>
		         <!--    <el-col class="line" :span="2">-</el-col>
		            <el-col :span="11">
		                <el-form-item prop="date2">
		                    <el-time-picker type="fixed-time" placeholder="选择时间" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker>
		                </el-form-item>
		            </el-col> -->
		        </el-form-item>

		        <el-form-item label="任务时长" prop="timer">
		        	<el-input-number v-model="ruleForm.timer"  :min="1" :max="1000" label="描述文字"></el-input-number>  <span>分钟</span>
		        </el-form-item>

		        <el-form-item label="活动形式" prop="desc">
		            <el-input type="textarea" resize='none' :rows='4' placeholder="在此输入任务内容,100个字符以内" maxlength="100" v-model="ruleForm.desc"></el-input>
		        </el-form-item>

		        <el-form-item class="buttonCSS" label-width="0" >
		        	<el-button @click="resetForm('ruleForm')" plain>取消</el-button>
		            <el-button type="primary" v-preventReClick="1000" @click="submitForm('ruleForm')">确定</el-button>
		           
		        </el-form-item>
		    </el-form>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				pickerOptionsStart: {
				    disabledDate: (time) => {
				        return time.getTime() < parseInt(Date.now() - 8.64e7);
				    }
				},
				videoData: [],
				page_index: 1,
				page_size: this.$g.page_size,
				total_sum: 0,
				placeholder: false,
				loading: true,
				videoList: [],

				classLsit: [],
				taskVisible: false,
				resource_id: '',
				ruleForm: {
				    name: '',
				    class_id: [],
				    date: '',
				    timer: '',
				    desc: ''
				},
				rules: {
				    name: [
				        { required: true, message: '请输入任务名称', trigger: 'blur' },
				    ],
				    class_id: [
				        { type: 'array', required: true, message: '请至少选择一个任务对象', trigger: 'change' }
				    ],
				    date: [
				        { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
				    ],
				    timer: [
				        { required: true, message: '请输入任务时长', trigger: 'blur' },
				    ],
				    desc: [
				        { required: true, message: '请填写活动形式', trigger: 'blur' }
				    ]
				},
			}
		},
		created(){
			this.get_videoList()
		},
		methods: {
			/*
			    查看
			 */
			checkLook(item, id, type){
			    // let BASE_URL = sessionStorage.getItem('host_addr')
			    // let redirect_params = sessionStorage.getItem( 'redirect_params' )

			    let host = sessionStorage.getItem( 'host' )
			    let redirectParams = sessionStorage.getItem( 'redirect_params' )

			    let link = ''


			    switch(type){
			        case 0: 
						this.goToDetailPage(item.status_m3u8, id)//全局跳转公开课视频的方法
			            break;
			        case 1: 
			             // window.open(BASE_URL+'/index/test/test_detail?testid='+id);
			            link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/test/details&id=${id}`
			            window.open(link)
			            break;
			        case 2: 
			              // window.open(BASE_URL+'/index/resource/detail?resourceid='+id);
			              link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/home/resourceDetail&id=${id}`
			              window.open(link)
			            break;
			    }

			     
			},
			newTaskVisible(id){
				this.taskVisible = true
				this.resource_id = id
				this.get_class()
			},
			get_class(){
				let success = (res=>{
					this.classLsit = res.data
				});
				this.$ajax({
					url: 'api/org/class_userid',
					method: 'get',
					params: { user_id: this.$g.user_id},
					func: {success: success}
				})
			},
			submitForm(formName) {

				this.$refs[formName].validate((valid) => {
					if (valid) {
						let timestampToTime = deep_clone(this.ruleForm.date)
						let success = (res =>{
							this.taskVisible = false
							this.$message.success(res.msg)
						})
						let params = {
							userid: this.$g.user_id,
							videoid: `${this.resource_id},0`,
							classid: this.ruleForm.class_id,
							end_time: formatTime(timestampToTime),
							task_name: this.ruleForm.name,
							length: this.ruleForm.timer,
							profile: this.ruleForm.desc,
							prepare_id: this.$route.query.id

						}

						this.$ajax.post('api/prepare/prepare_task', params, { func: { success: success } })
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm(formName) {
				this.taskVisible = false
				// this.$refs[formName].resetFields();
			},
			removeDate(id){
			    this.$confirm('确认执行此操作?', '提示', {
			        confirmButtonText: '确定',
			        cancelButtonText: '取消',
			        customClass: 'removeing'
			    }).then(() => {
			        let success = (res => {     
			            this.$message.success(res.msg)
			            this.get_videoList()
			        })
			        this.$ajax({
			            url: 'api/prepare/del_prepare_resource',
			            method: 'delete',
			            params: {
			            	res_id: id,
			                prepareid: this.$route.query.id,
			               userid: this.$g.user_id,
			               origin: 0
			            },
			            func:{
			                success:success
			            }
			        })
			    }).catch(() => {});
			},
			get_videoList(){
				let success = (res=>{
					this.videoList = res.data.data;
					this.total_sum = parseInt(res.data.data_sum)

					this.loading = false;
					this.videoList.length === 0 ? this.placeholder = true : this.placeholder = false
				});
				this.$ajax({
					url: 'api/prepare/prepare_resource_list',
					method: 'get',
					params: {
						prepareid: this.$route.query.id,
						userid: this.$g.user_id,
						page_index: this.page_index,
						page_size: this.page_size,
						origin: 0
					},
					func: {success: success}
				})
			},
			goBack(){
			    this.$router.back(-1)
			},
			sizeChange(val) {
				this.page_index = val;
				this.get_videoList()
				// console.log(`当前页: ${val}`);
			},
			download(type,trainid){
				switch(type){
					case 0: 
						return `${this.BASE_URL}/index/openclass/videodownload?id=${trainid}`;
						break;
					case 1: 
						return `${this.BASE_URL}/index/test/download_test?id=${trainid}`;
						break;
					case 2: 
						return `${this.BASE_URL}/index/resource/resourcedownload?id=${trainid}`;
						break;
				}
			},
			getDateTimeStamp (dateStr) {
			    return Date.parse(dateStr.replace(/-/gi,"/"));
			},
			getDateDiff (dateStr) {
			    var publishTime = this.getDateTimeStamp(dateStr)/1000,
			        Dseconds,
			        Dminutes,
			        Dhours,
			        Ddays,
			        timeNow = parseInt(new Date().getTime()/1000),
			        d,

			        date = new Date(publishTime*1000),
			        Y = date.getFullYear(),
			        M = date.getMonth() + 1,
			        D = date.getDate(),
			        H = date.getHours(),
			        m = date.getMinutes(),
			        s = date.getSeconds();
			        //小于10的在前面补0
			        if (M < 10) {
			            M = '0' + M;
			        }
			        if (D < 10) {
			            D = '0' + D;
			        }
			        if (H < 10) {
			            H = '0' + H;
			        }
			        if (m < 10) {
			            m = '0' + m;
			        }
			        if (s < 10) {
			            s = '0' + s;
			        }

			    d = timeNow - publishTime;
			    Ddays = parseInt(d/86400);
			    Dhours = parseInt(d/3600);
			    Dminutes = parseInt(d/60);
			    Dseconds = parseInt(d);

			    if(Ddays > 0 && Ddays < 3){
			          return M + '-' + D + ' ' + H + ':' + m;
			    }else if(Ddays <= 0 && Dhours > 0){
			       return '昨天'+ ' ' + H + ':' + m;
			    }else if(Dhours <= 0 && Dminutes > 0){
			         return H + ':' + m;
			    }else if (Dseconds < 60) {
			    	return '刚刚';
			        if (Dseconds <= 0) {
			        	 return '';
			        }else {
			        	   return '';
			        }
			    }else if (Ddays >= 3 && Ddays < 30){
			        return M + '-' + D + ' ' + H + ':' + m;
			    }else if (Ddays >= 30) {
			        // return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
			        return M + '-' + D + ' ' + H + ':' + m;
			    }
			},
		}
	}
</script>